<template>
   <view style="opacity: .999">
     <image class="width-full height-full bg" :src="imgUrl || imageSrc" @error="handleLoadError" :mode="mode" @click.stop="$emit('click')" />
   </view>
</template>

<script>

export default {
  props: {
    imageSrc: {
      type: String
    },
    cache: {
      type: Boolean,
      default: true
    },
    cacheTime: {
      type: Number
    },
    delay: {
      type: Number,
      default: 1
    },
    mode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imgUrl: ''
    }
  },
  computed: {
    useCache() {
      // 判断环境
      let inH5 = false
      // #ifdef H5
      inH5 = true
      // #endif
      // 判断是否使用缓存
      return !inH5 && this.cache
    }
  },
  watch: {
    // #ifndef H5
    imageSrc: {
      handler(src) {
        if (!this.useCache) return
        this.handleCache(src)
      },
      immediate: true
    }
    // #endif
  },
  methods: {
    async handleCache(src) {
      if (!src) return

      const sign = 'cached-image'
      const cachedRes = uni.getStorageSync(sign + src)
      if (cachedRes && this.cacheTime) {
        const cachedUrlInfo = await uni.getSavedFileInfo({ filePath: cachedRes })
        const createTime = cachedUrlInfo[1] && cachedUrlInfo[1].createTime
        const expiredTime = createTime + this.cacheTime * 24 * 60 * 60 * 1000
        if (expiredTime > +new Date()) {
          // console.log('缓存未过期');
          this.imgUrl = cachedRes
          return
        } else if (expiredTime) {
          // 删除缓存过期的图片
          uni.removeSavedFile({ filePath: cachedRes })
          uni.removeStorageSync(sign + src)
        }
      } else if (cachedRes && !this.cacheTime) {
        this.imgUrl = cachedRes
        return
      }

      setTimeout(() => {
        uni.downloadFile({ url: src }).then(res => {
          if (res.statusCode === 200) {
            uni.saveFile({
              tempFilePath: res.tempFilePath
            }).then(res1 => {
              uni.setStorage({
                key: sign + src,
                data: res1.savedFilePath
              })
            })
          } else {
            return Promise.reject('下载临时文件失败')
          }
        })
      }, this.delay * 1000)
    },
    handleLoadError() {
      if (this.imgUrl) {
        // 如果使用缓存地址加载失败的话换回默认源地址
        this.imgUrl = ''
      } else {
        // 加载失败图的base64码
        this.imgUrl = ''
      }
    }

  }
}
</script>

<style scoped>
.bg{
  background: #F6F6F6;
}
</style>
